<template>
  <div class="user-management-container">
    <!-- 搜索区域-->
    <el-row>
      <el-form ref="form" :model="queryParams" label-width="80px">
        <el-col :span="6">
          <el-form-item label="主体名称">
            <el-input v-model="queryParams.companyName" size="small" placeholder="请输入主体名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册手机">
            <el-input v-model="queryParams.mobilePhone" size="small" placeholder="请输入注册手机号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否会员">
            <el-select v-model="queryParams.memberFlag" size="small" placeholder="请选择是否会员" style="width: 240px">
<!--              原生开发方式：数据固定，一旦需要有变动都需要修改源码-->
<!--              <el-option label="非会员" :value="0"></el-option>-->
<!--              <el-option label="会员" :value="1"></el-option>-->

<!--              使用字典方式： 数据动态化-->
              <el-option
                  v-for="dict in dict.type.njt_member_flag"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="toggleContent">
          <el-col :span="6">
            <el-form-item label="用户状态">
              <el-select v-model="queryParams.userStatus" size="small" placeholder="请选择用户状态"
                         style="width: 240px">
<!--                <el-option label="正常" :value="0"></el-option>-->
<!--                <el-option label="冻结" :value="1"></el-option>-->
                <el-option
                  v-for="dict in dict.type.njt_user_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="6">
          <el-form-item label-width="0" style="margin-left: 20px">
            <el-button type="primary" icon="el-icon-search" size="small" style="margin-right: 10px" @click="getPage()">
              搜索
            </el-button>
            <el-button type="primary" icon="el-icon-refresh" size="small" @click="resetForm">重置</el-button>
            <a style="margin-left: 10px;color: #3a8ee6" @click="toggleContentHandle">
              {{ toggleContent ? '收起' : '展开' }}
              <i v-if="toggleContent" class="el-icon-arrow-up"></i>
              <i v-else class="el-icon-arrow-down"></i>
            </a>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <!-- 操作按钮组-->
    <el-row style="margin-top: 10px;">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-download" size="medium" style="margin-right: 10px" @click="handleExport">导出</el-button>
        <el-button type="danger" icon="el-icon-delete" size="medium" @click="batchDelete">批量删除</el-button>
      </el-col>
    </el-row>
    <!-- 表格区域-->
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <el-table ref="userTable" :data="tableData" style="width: 100%" border>
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="companyName" label="主体名称" align="center"></el-table-column>
          <el-table-column prop="mobilePhone" label="注册手机号" align="center"></el-table-column>
          <el-table-column prop="registerTime" label="注册时间" align="center"></el-table-column>
          <el-table-column label="公司logo" align="center">
            <template slot-scope="scope">
                <image-preview
                  src="http://t2zgcg68q.hn-bkt.clouddn.com/445b273ab45b64f2998f0cf15566898f525661848_raw.jpg" width="50" height="80"/>
            </template>
          </el-table-column>
          <el-table-column label="是否会员" align="center">
            <template slot-scope="scope">
<!--              <el-tag type="danger" v-if="scope.row.memberFlag === 0">非会员</el-tag>-->
<!--              <el-tag type="success" v-else-if="scope.row.memberFlag === 1">会员</el-tag>-->
<!--              <el-tag type="info" v-else>错误</el-tag>-->
              <dict-tag :options="dict.type.njt_member_flag" :value="scope.row.memberFlag"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="信息是否完善" align="center">
            <template slot-scope="scope">
<!--              原生开发方式：数据翻译静态化，一旦需要有变动，都需要二次开发源码-->
<!--              <el-tag type="danger" v-if="scope.row.perfectFlag === 0">未完善</el-tag>-->
<!--              <el-tag type="success" v-else-if="scope.row.perfectFlag === 1">已完善</el-tag>-->
              <dict-tag :options="dict.type.njt_perfect_flag" :value="scope.row.perfectFlag"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="用户状态" align="center">
            <template slot-scope="scope">
<!--              <el-tag type="success" v-if="scope.row.userStatus === 0">正常</el-tag>-->
<!--              <el-tag type="danger" v-else-if="scope.row.userStatus === 1">冻结</el-tag>-->
              <dict-tag :options="dict.type.njt_user_status" :value="scope.row.userStatus"></dict-tag>

            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="220" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteByUserId(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 分页区域-->
    <el-row>
      <el-col :span="24" style="margin-top: 20px" align="center">
        <el-pagination layout="prev, pager, next" :page-size="queryParams.pageSize" :total="total"
                       :current-page="queryParams.pageNum" @current-change="getPageByPageNum"></el-pagination>
      </el-col>
    </el-row>
    <!-- 弹窗区域：一般用于新增或编辑弹窗-->
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="30%">
      <!--添加表单组件-->
      <el-form ref="updateForm" :model="editObjects" label-width="100px">
        <el-form-item label="主体名称">
          <el-input v-model="editObjects.companyName" placeholder="请输入主体名称"></el-input>
        </el-form-item>
        <el-form-item label="注册手机号">
          <el-input v-model="editObjects.mobilePhone" placeholder="请输入注册手机号"></el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-input v-model="editObjects.registerTime" placeholder="请输入注册时间"></el-input>
        </el-form-item>
        <el-form-item label="是否会员">
          <el-select v-model="editObjects.memberFlag" placeholder="请选择是否会员">
<!--            <el-option label="非会员" :value="0"></el-option>-->
<!--            <el-option label="会员" :value="1"></el-option>-->
            <el-option
              v-for="dict in dict.type.njt_member_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信息是否完善">
          <el-select v-model="editObjects.perfectFlag" placeholder="请选择信息是否完善">
<!--            <el-option label="未完善" :value="0"></el-option>-->
<!--            <el-option label="已完善" :value="1"></el-option>-->
            <el-option
              v-for="dict in dict.type.njt_perfect_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select v-model="editObjects.userStatus" placeholder="请选择用户状态">
<!--            <el-option label="正常" :value="0"></el-option>-->
<!--            <el-option label="冻结" :value="1"></el-option>-->
            <el-option
              v-for="dict in dict.type.njt_user_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信息完善时间">
          <el-input v-model="editObjects.infoCompleteTime" placeholder="请输入信息完善时间"></el-input>
        </el-form-item>
        <el-form-item label="试用到期时间">
          <el-input v-model="editObjects.trialEndTime" placeholder="请输入试用到期时间"></el-input>
        </el-form-item>
        <el-form-item label="购买会员时间">
          <el-input v-model="editObjects.memberBuyTime" placeholder="请输入购买会员时间"></el-input>
        </el-form-item>
        <el-form-item label="会员过期时间">
          <el-input v-model="editObjects.memberEndTime" placeholder="请输入会员过期时间"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框底部按钮组，固定代码结构-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {deleteNjtUserRegister, listNjtUserRegister, updateNjtUserRegister} from "@/api/njt/user/register";
import Dict from "@/views/system/dict/index.vue";

export default {
  name: "UserManagement",
  components: {Dict},
  dicts: ["njt_member_flag","njt_perfect_flag","njt_user_status"],
  data() {
    return {
      props: {
        src: {
          type: String,
          default: ""
        },
        width: {
          type: [Number, String],
          default: ""
        },
        height: {
          type: [Number, String],
          default: ""
        }
      },
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        companyName: "",
        mobilePhone: "",
        memberFlag: undefined,
        userStatus: undefined
      },
      toggleContent: false,
      tableData: [
        {
          id: 1,
          companyName: "我的测试公司地址",
          mobilePhone: "138****5678",
          registerTime: "2021-10-29 15:42:15",
          memberFlag: 1,
          perfectFlag: 1,
          userStatus: 0,
          infoCompleteTime: "2021-10-29 15:43:00",
          trialEndTime: "2023-10-29",
          memberBuyTime: "2021-10-29",
          memberEndTime: "2023-10-29"
        }
      ],
      total: 56,
      dialogVisible: false,
      editObjects: {
        companyName: "",
        mobilePhone: "",
        registerTime: "",
        memberFlag: undefined,
        perfectFlag: undefined,
        userStatus: undefined,
        infoCompleteTime: "",
        trialEndTime: "",
        memberBuyTime: "",
        memberEndTime: ""
      }
    };
  },
  created() {
    this.getPage();
  },
  methods: {
    handleExport(){
      this.download('/nongjt/userRegister/export', {
        ...this.queryParams
      }, `会员注册信息_${new Date().getTime()}.xlsx`);
    },
    /**
     * 根据用户ID删除单个用户 (调用通用删除方法)
     * @param {number} userId - 用户ID
     */
    deleteByUserId(userId) {
      // 调用通用删除方法，并传入一个只包含当前ID的数组
      this.handleDelete([userId]);
    },
    /**
     * 批量删除用户
     */
    batchDelete() {
      const selectedRows = this.$refs.userTable.selection;
      if (!selectedRows || selectedRows.length === 0) {
        this.$modal.msgWarning("请至少选择一条记录进行删除！");
        return;
      }
      const idsToDelete = selectedRows.map(row => row.id);
      this.handleDelete(idsToDelete);
    },

    /**
     * 通用删除处理方法（支持单个和批量）
     * @param {Array<number>} ids - 要删除的用户ID数组
     */
    handleDelete(ids) {
      this.$modal.confirm(`您确定要删除选中的 ${ids.length} 条数据吗？`).then(() => {
        // 将ids数组包装成对象
        return deleteNjtUserRegister({ids: ids});
      }).then(response => {
        this.$modal.msgSuccess(response.msg || "删除成功");
        this.getPage();
      }).catch(() => {
        // 取消或失败不做特殊处理
      });
    },

    /**
     * 提交编辑表单
     */
    submitData() {
      updateNjtUserRegister(this.editObjects).then(responses => {
        this.getPage();
        this.$modal.msgSuccess(responses.msg);
        this.dialogVisible = false;
      });
    },

    /**
     * 分页页码切换
     */
    getPageByPageNum(num) {
      this.queryParams.pageNum = num;
      this.getPage();
    },

    /**
     * 切换搜索内容显示/隐藏
     */
    toggleContentHandle() {
      this.toggleContent = !this.toggleContent;
    },

    /**
     * 打开编辑对话框
     */
    openDialog(objData) {
      this.editObjects = {...objData};
      this.dialogVisible = true;
    },

    /**
     * 分页查询
     */
    getPage() {
      listNjtUserRegister(this.queryParams).then(response => {
        this.tableData = response.rows.map(row => ({
          ...row,
          companyName: row.companyName || row.subjectName || "",
          mobilePhone: row.mobilePhone || row.phone || ""
        }));
        this.total = response.total;
      });
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        companyName: "",
        mobilePhone: "",
        memberFlag: undefined,
        userStatus: undefined
      };
      this.getPage();
    }
  }
};
</script>

<style scoped>
/* 自定义样式使表格更美观 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

::v-deep .el-tag {
  padding: 0 6px;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
}

::v-deep .el-dropdown-link {
  color: #409eff;
  cursor: pointer;
}

/* 操作列按钮样式 */
::v-deep .el-table .el-button--text {
  padding: 0 5px;
}
</style>
